// 提醒事项模块
import React, { useEffect, useRef } from 'react'
import { StoreState } from '../../../store'
import MyTable from '../../../components/table/table'
import moment from 'moment'
import CreateReminder from './createreminder/createreminder'
import useKeepState from 'use-keep-state'
import { connect } from 'react-redux'
import { DatePicker, Button, Select, Tag, Modal, Form, Popconfirm } from 'antd'
import {
  serviceGetReminder,
  serviceDeleteReminder,
} from '../../../request/reminder'

const { RangePicker } = DatePicker
// 查询类型
const { Option } = Select
const DATE_FORMAT = 'YYYY-MM-DD'
const STATUS_TYPE: any = {
  1: { color: '#f50', text: '待提醒' },
  2: { color: '#87d068', text: '已提醒' },
}

interface State {
  showCreateModal: boolean
  currentRow: { [key: string]: any } | null
}

const mapStateToProps = (store: StoreState) => ({
  userInfo: store.user.userInfo,
})

type Props = ReturnType<typeof mapStateToProps>

const initialState: State = {
  showCreateModal: false,
  currentRow: null,
}

const Reminder: React.FC<Props> = function ({ userInfo }: Props) {
  const [form] = Form.useForm()
  const [state, setState] = useKeepState(initialState)
  const tableRef = useRef<any>()
  // 点击编辑、删除按钮
  function handleButton(type: number, rows: any) {
    // 编辑
    if (type === 0) {
      setState({
        showCreateModal: true,
        currentRow: rows,
      })
    } else if (type === 1) {
      // 删除
      serviceDeleteReminder(rows.id).then(res => {
        if (res.data.success) {
          tableRef.current.getTableData()
        }
      })
    }
  }
  // modal成功 回调函数
  function handleModalOnSuccess() {
    setState({ showCreateModal: false })
    tableRef.current.getTableData()
  }
  const tableColumns = [
    {
      title: '序号',
      width: 60,
      render: (currentRowValue: any, currentRowData: any, index: number) =>
        index + 1,

      align: 'center',
    },
    {
      title: '状态',
      // dataIndex：列数据在dataSource中对应的路径（字段名）
      // 设置了dataIndex，则render函数的第一个参数即是dataIndex对应的字段名的值，第二参数则是该行的数据对象
      // 如果没有设置dataIndex，则render函数的第一个参数和第二个参数都是该行的数据对象
      dataIndex: 'type',
      width: 100,
      align: 'center',
      render: (currentRowValue: any) => (
        <Tag color={STATUS_TYPE[currentRowValue].color}>
          {STATUS_TYPE[currentRowValue].text}
        </Tag>
      ),
    },
    {
      title: '提醒时间',
      dataIndex: 'createdAt',
      width: 220,
      align: 'center',
    },
    {
      title: '提醒内容',
      dataIndex: 'content',
      className: 'wbba wpr', // global.scss  wbba:允许在单词内换行  wpr:保留空格和换行符
      ellipsis: true,
    },
    {
      title: '操作',
      width: 180,
      align: 'center',
      fixed: 'right',
      render: (currentRowValue: any) => (
        <>
          <Button onClick={handleButton.bind(null, 0, currentRowValue)}>
            编辑
          </Button>
          <Popconfirm
            title="您确定要删除吗？"
            onConfirm={handleButton.bind(null, 1, currentRowValue)}
            placement="bottomLeft"
            okType="danger"
          >
            <Button>删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ]

  // 点击重置按钮
  function initParams() {
    // 设置为今年一月1日上午 12:00
    const startDate = moment().startOf('year')
    // 设置为今年的 12 月 31 日 23:59:59.999
    const endDate = moment().endOf('year')
    form.setFieldsValue({
      queryType: '',
      date: [startDate, endDate],
    })
    tableRef?.current?.getTableData()
  }

  function getReminder(params: any = {}) {
    // 获取一组字段名对应的值，会按照对应结构返回。
    const values = form.getFieldsValue()
    if (values.date && values.date.length === 2) {
      params.startDate = values.date[0].format(DATE_FORMAT)
      params.endDate = values.date[1].format(DATE_FORMAT)
    }
    if (values.queryType !== '') {
      params.type = values.queryType
    }
    return serviceGetReminder(params).then(res => {
      if (res.data.success) {
        res.data.data.rows = res.data.data.rows.map(
          (item: any, index: number) => {
            item.order = index + 1
            item.createdAt = moment(item.createdAt).format(
              'YYYY-MM-DD HH:mm:ss',
            )
            return item
          },
        )
      }
      return res
    })
  }
  useEffect(() => {
    initParams()
    if (!userInfo.email) {
      Modal.warning({
        title: '未检测到您的邮箱',
        content: (
          <>
            请将您的Github邮箱设为公开，否则影响本功能的使用
            <a
              href="https://github.com/settings/profile"
              target="_blank"
              rel="noopener noreferrer"
            >
              前往设置
            </a>
          </>
        ),
      })
    }
  }, [userInfo.email])

  return (
    <div className="reminder">
      {/* 顶部查询模块 */}
      <div className="query-panel">
        {/* inline是表单元素都在一行 */}
        <Form
          form={form}
          layout="inline"
          onValuesChange={() => tableRef?.current?.getTableData()}
        >
          {/* 查询类型 */}
          <Form.Item name="queryType" label="查询类型" initialValue="">
            <Select>
              <Option value="">全部</Option>
              <Option value="1">待提醒</Option>
              <Option value="2">已提醒</Option>
            </Select>
          </Form.Item>
          {/* 选择日期 */}
          <Form.Item name="date" label="日期">
            <RangePicker allowClear></RangePicker>
          </Form.Item>
          {/* 查询，重置 */}
          <Form.Item>
            <Button
              type="primary"
              onClick={() => tableRef.current.getTableData()}
            >
              查询
            </Button>
            <Button onClick={initParams}>重置</Button>
          </Form.Item>
        </Form>
      </div>
      <MyTable
        ref={tableRef}
        getTableData={getReminder}
        columns={tableColumns}
        onAdd={() => setState({ showCreateModal: true, currentRow: null })}
        onDelete={serviceDeleteReminder}
      ></MyTable>
      <CreateReminder
        visible={state.showCreateModal}
        rowData={state.currentRow}
        onSuccess={handleModalOnSuccess}
        onCancel={() => setState({ showCreateModal: false })}
      ></CreateReminder>
    </div>
  )
}

export default connect(mapStateToProps)(Reminder)
